package model

import (
	ryrpc "admin/rpc"
	"common/helper"
	"database/sql"
	"errors"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/doug-martin/goqu/v9/exp"
	"sort"
)

type TurntableInfo struct {
	Reward float64 `json:"reward"`
	Count  int     `json:"count"`
	Remark string  `json:"remark"`
}

func TurnTableReviewList(startTime, endTime string, ex g.Ex, timeType, page, pageSize int) (ryrpc.TurntableReviewData, error) {

	data := ryrpc.TurntableReviewData{}

	startAt, err := helper.TimeToLoc(startTime, loc)
	if err != nil {
		return data, errors.New(helper.TimeTypeErr)
	}

	endAt, err := helper.TimeToLoc(endTime, loc)
	if err != nil {
		return data, errors.New(helper.TimeTypeErr)
	}

	if startAt >= endAt {
		return data, errors.New(helper.QueryTimeRangeErr)
	}
	if timeType == 1 {
		ex["apply_at"] = g.Op{
			"between": exp.NewRangeVal(startAt, endAt),
		}
	} else {
		ex["review_at"] = g.Op{
			"between": exp.NewRangeVal(startAt, endAt),
		}
	}

	t := dialect.From("tbl_pdd_turntable_review")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT("id")).Where(ex).ToSQL()

		err = meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsTurntableReview...).Where(ex).Order(g.C("review_at").Desc(), g.C("apply_at").Desc()).Offset(uint(offset)).Limit(uint(pageSize)).ToSQL()

	err = meta.MerchantDB.Select(&data.D, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return data, nil
}

func TurnTableReview(state string, record g.Record) error {
	return nil
}

func GetTurntableInfo(uid string) (ryrpc.TblPddTurntableInfo, error) {

	var data ryrpc.TblPddTurntableInfo
	query, _, _ := dialect.From("tbl_pdd_turntable_info").Select(colsTurntableInfo...).Where(g.Ex{"uid": uid}).Limit(1).ToSQL()

	err := meta.MerchantDB.Get(&data, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	if err == sql.ErrNoRows {
		return data, errors.New(helper.UIDErr)
	}
	data.RewardAmount = data.Amount + data.HandAmount

	return data, nil
}

func TurnTableHistoryList(startTime, endTime string, ex g.Ex, page, pageSize int) (ryrpc.TurntableHistoryData, error) {

	data := ryrpc.TurntableHistoryData{}

	startAt, err := helper.TimeToLoc(startTime, loc)
	if err != nil {
		return data, errors.New(helper.TimeTypeErr)
	}

	endAt, err := helper.TimeToLoc(endTime, loc)
	if err != nil {
		return data, errors.New(helper.TimeTypeErr)
	}

	if startAt >= endAt {
		return data, errors.New(helper.QueryTimeRangeErr)
	}

	t := dialect.From("tbl_pdd_turntable_history")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT("id")).Where(ex).ToSQL()

		err = meta.MerchantDB.Get(&data.T, query)
		if err != nil {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if data.T == 0 {
			return data, nil
		}
	}

	offset := (page - 1) * pageSize
	query, _, _ := t.Select(colsTurntableHistory...).Where(ex).Order(g.C("created_at").Desc()).Offset(uint(offset)).Limit(uint(pageSize)).ToSQL()

	err = meta.MerchantDB.Select(&data.D, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	return data, nil
}

type TurnTableData struct {
	T int                   `json:"total"`
	D []TurnTableStatistics ` json:"d"`
	S int                   `json:"s"`
}

type TurnTableStatistics struct {
	Uid               string  `json:"uid"`
	InviteRegisterNum int     `json:"invite_register_num"` //邀请注册人数
	InviteRechargeNum int     `json:"invite_recharge_num"` //邀请充值人数(充值达到最低首充金额)
	DepositAmount     float64 `json:"deposit_amount"`      //充值金额
	WithdrawAmount    float64 `json:"withdraw_amount"`     //取款金额
	DwDiff            float64 `json:"dw_diff"`             //充提差
	Amount            float64 `json:"amount"`              //奖励金额
	HandAmount        float64 `json:"hand_amount"`         //手动奖励金额
}

func TurnTableReport(page, pageSize int, uid, userName string) (TurnTableData, error) {

	var data TurnTableData

	data.S = pageSize
	ex := g.Ex{}
	if userName != "" {
		ex["username"] = userName
	}
	if uid != "" {
		ex["uid"] = uid
	}

	t := dialect.From("tbl_pdd_turntable_info")
	if page >= 1 {
		query, _, _ := t.Select(g.COUNT("uid")).Where(ex).ToSQL()

		err := meta.MerchantDB.Get(&data.T, query)
		if err != nil && err != sql.ErrNoRows {
			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
		}

		if errors.Is(err, sql.ErrNoRows) || data.T == 0 {
			return data, nil
		}
	}
	offset := (uint(page) - 1) * uint(pageSize)
	var d []ryrpc.TblPddTurntableInfo
	query, _, _ := t.Select(colsTurntableInfo...).Where(ex).Order(g.I("created_at").Desc()).Offset(offset).Limit(uint(pageSize)).ToSQL()
	err := meta.MerchantDB.Select(&d, query)
	if err != nil {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	if len(d) == 0 {
		return data, nil
	}
	for _, v := range d {
		m, err := MemberFindByUid(v.Uid)
		if err != nil {
			return data, err
		}
		statistics := TurnTableStatistics{
			Uid:            m.Uid,
			DepositAmount:  m.DepositAmount,
			WithdrawAmount: v.TotAmount,
			DwDiff:         m.DepositAmount - v.TotAmount,
			Amount:         v.Amount,
			HandAmount:     v.HandAmount,
		}
		data.D = append(data.D, statistics)
	}
	sort.Sort(ByDepositAmount(data.D))
	return data, nil
}

// 按照充值金额降序排序
type ByDepositAmount []TurnTableStatistics

func (a ByDepositAmount) Len() int           { return len(a) }
func (a ByDepositAmount) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByDepositAmount) Less(i, j int) bool { return a[i].DepositAmount > a[j].DepositAmount }
